<template>
  <div class="setting-editPw">
    <el-dialog :visible.sync="centerDialogVisible"
               :close-on-click-modal="clickModalHide"
               :before-close="closeDialog" width="390px"
               title="修改密码">

      <el-form :model="editData" status-icon :rules="rules" ref="editData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名：" prop="userAccount">
          <el-input v-model="editData.userAccount" disabled></el-input>
        </el-form-item>
        <!--<el-form-item label="旧密码" prop="oldPassword">-->
          <!--<el-input v-model="editData.oldPassword" type="password" ></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="新密码：" prop="password">
          <el-input v-model="editData.password" type="password" ></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPass">
          <el-input v-model="editData.checkPass" type="password" ></el-input>
        </el-form-item>
        <el-form-item label="验证码：" >
          <el-input v-model="code" ></el-input>
          <canvas id="canvas" width="80" height="30" @click="drawCode()" style="border: 1px solid #ccc;border-radius: 5px;"></canvas>
        </el-form-item>
        <el-form-item style="text-align: center;padding-bottom: 5px">
          <el-button type="primary" @click="submitForm('editData')">提交</el-button>
          <el-button @click="resetForm('editData')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import { getToken } from '@/utils/auth' // 验权
  import { removeToken } from '@/utils/auth' // 验权
  export default {
    props:['data'],
    name:'editPw',
    data(){
      var notEmpty = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }else{
          callback();
        }
      };

      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.editData.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };

      return{
        centerDialogVisible: false,
        clickModalHide: false,
        editData:{
          userAccount:"",
          password:"",
          oldPassword:"",
          checkPass:"",
        },
        code:"",
        show_num:[],
        rules: {
          userAccount: [
            { validator: notEmpty, trigger: 'blur' }
          ],
          password: [
            { validator: notEmpty, trigger: 'blur' }
          ],
          oldPassword: [
            { validator: notEmpty, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ]
        },
      }
    },


    methods:{

      randomColor(){
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
      },

      drawCode(){
        var canvas_width=document.getElementById('canvas').clientWidth;
        var canvas_height=document.getElementById('canvas').clientHeight;
        var canvas = document.getElementById("canvas");//获取到canvas的对象，演员
        var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
        canvas.width = canvas_width;
        canvas.height = canvas_height;
        var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
        var aCode = sCode.split(",");
        var aLength = aCode.length;//获取到数组的长度

        for (var i = 0; i <= 3; i++) {
          var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
          var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
          var txt = aCode[j];//得到随机的一个内容
          this.show_num[i] = txt;
          var x = 2 + i * 20;//文字在canvas上的x坐标
          var y = 17 + Math.random() * 8;//文字在canvas上的y坐标
          context.font = "bold 23px 微软雅黑";

          context.translate(x, y);
          context.rotate(deg);

          context.fillStyle = this.randomColor();
          context.fillText(txt, 0, 0);

          context.rotate(-deg);
          context.translate(-x, -y);
        }
        for (var i = 0; i <= 5; i++) { //验证码上显示线条
          context.strokeStyle = this.randomColor();
          context.beginPath();
          context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
          context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
          context.stroke();
        }
        for (var i = 0; i <= 30; i++) { //验证码上显示小点
          context.strokeStyle = this.randomColor();
          context.beginPath();
          var x = Math.random() * canvas_width;
          var y = Math.random() * canvas_height;
          context.moveTo(x, y);
          context.lineTo(x + 1, y + 1);
          context.stroke();
        }
      },

      operateLogin(){
        let self = this;
        self.$http({
          url: "/autoMonitor/user/updatePassword",
          method: "post",
          params:self.editData
        }).then(resp => {
          if (resp.success) {
            self.$notify({
              title: '提示',
              message: "修改成功！",
              type: 'success'
            });
            self.closeDialog();
            let user = JSON.parse(getToken());
            if(user.userAccount == self.editData.userAccount){
              self.loginOut();
            }
            return
          }
          self.$notify({
            title: '提示',
            message: "密码错误！",
            type: 'error'
          });
        });
      },

      loginOut(){
        let self =this;
        self.$http({
          url: "/autoMonitor/loginOut",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.$store.dispatch('LogOut').then(() => {
              removeToken();
              location.reload()
            })
          }
        });
      },

      //关闭弹窗
      closeDialog() {
        this.centerDialogVisible = false;
      },

      submitForm(formName) {
        let self = this;
        if(this.show_num.join("").toLocaleLowerCase() != this.code.toLocaleLowerCase()){
          self.$notify({
            title: '提示',
            message: "验证码错误！",
            type: 'error'
          });
          return;
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            self.operateLogin();
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].clearValidate();
        this.closeDialog();
      }

    },
    watch:{
      data(val){
        let self = this;
        this.code = "";
        this.show_num = [];
        self.$nextTick(()=>{
          self.$refs["editData"].clearValidate();
          self.drawCode();
        });
        this.centerDialogVisible = true;
        this.editData.userAccount = val.userAccount;
      }
    }
  }
</script>
<style>
  .setting-editPw .el-dialog__body {
    padding-left: 0 !important;
  }

  .setting-editPw .el-form-item {
    margin-bottom: 8px;
  }

  .setting-editPw .el-input--medium .el-input__inner{
    height: 28px;
  }

  .setting-editPw .el-button--medium {
    padding: 6px 16px;
  }

  .setting-editPw .el-form-item__error{
    padding-top:0px
  }
</style>
